#include "app_file.h"

const struct fal_partition *font_addr;

#define FILESYS_PART_NAME "filesystem"
#define FN_IN_PIN1	GET_PIN(B,10)
#define FN_IN_PIN2 	GET_PIN(B,11)

extern int stm_usbd_register(void);
extern int rt_usbd_msc_class_register(void);

extern uint8_t lv_load_img_bin_from_file(lv_img_dsc_t *image, const char *file_name);

uint8_t *font_sdram = RT_NULL;

extern int stm_usbd_register(void);
extern int rt_usbd_msc_class_register(void);

int file_init_entry(void)
{
		struct rt_device *block_dev = RT_NULL;

		rt_pin_mode(FN_IN_PIN1,PIN_MODE_INPUT_PULLDOWN);
		rt_pin_mode(FN_IN_PIN2,PIN_MODE_INPUT_PULLDOWN);
		
		fal_init();
		
		font_addr = fal_partition_find("font");
		
		block_dev = fal_blk_device_create(FILESYS_PART_NAME);
		if (!block_dev)
    {
        rt_kprintf("Can't create a block device");
				return RT_ERROR;
    }
    else
    {
        
        if (dfs_mount(FILESYS_PART_NAME, "/", "elm", 0, 0) == 0)
        {
            rt_kprintf("Filesystem initialized!\n");
        }
        else
        {
           
            dfs_mkfs("elm",FILESYS_PART_NAME);
            
            if (dfs_mount(FILESYS_PART_NAME, "/", "elm", 0, 0) == 0)
            {
                rt_kprintf("Filesystem initialized!");
            }
            else
            {
                rt_kprintf("Failed to initialize filesystem!");
            }
        }
    }
		
		if(rt_pin_read(FN_IN_PIN1)  == PIN_HIGH)
		{
			rt_usbd_msc_class_register();
			stm_usbd_register();
		}
		easyflash_init();//init
		read_dev_config();//read info
		//load_font_to_sdram();//load font
		return RT_EOK;
}

INIT_ENV_EXPORT(file_init_entry);

void load_font_to_sdram(void)
{
		int fd;
		int ret;
		int size ;
		struct stat file_sta;
	
		fd = open("/FONT/FONT_ALIPH.bin", O_RDONLY);
		
		if (fd>= 0)
		{
			rt_kprintf("font file open successed\r\n");
			ret = stat("/FONT/FONT_ALIPH.bin", &file_sta);
			if(ret == 0)
			{
				rt_kprintf("FONT  file size = %d\n", file_sta.st_size);
				font_sdram = rt_malloc(file_sta.st_size);
				if(font_sdram == RT_NULL)
				{
					rt_kprintf("init font buffer failed!\n");
					return ;
				}
				
				size = read(fd, font_sdram,file_sta.st_size);
				
				if(size != file_sta.st_size)
				{
					rt_kprintf("read font size error!\n");
					return ;
				}
				
			}
			else
			{
				rt_kprintf("get file sta failed");
			}
		}
		else
		{
			rt_kprintf("font file open faiedr\r\n");
		}
}



